import {FormattedMessage, Helmet, Link, NavLink, Outlet, SelectLang, useSelectedRoutes, useNavigate} from 'umi';
import logo from "@/assets/img/logo.png"
import './index.less';
import React, {CSSProperties, useCallback, useMemo, useState} from "react";
import {Button, Divider, Popover, QRCode, Space, theme} from "antd";
import {ProConfigProvider} from "@ant-design/pro-provider";
import {ISelectedRoute} from "@umijs/renderer-react/dist/types";
import dayjs from "dayjs";
import HxIcon from "@/components/HxIcon";
import classNames from "classnames";
import {HxConfigContext, LayoutBgClassName} from "@/layouts/HxConfigContext";
import {useToken} from "antd/lib/theme/internal";
import FriendLinksContainer from "@/layouts/FriendLinksContainer";
import {useAccess, useIntl, useLocation, useModel, useRequest} from "@@/exports";
import * as API from "@/services";
import HeaderUserContainer from "@/layouts/HeaderUserContainer";
import {DEFAULT_LOGIN_PATH as LOGIN_PATH} from "@kf-web-library/utils/es/constants";
import {DEFAULT_REGISTER_PATH as REGISTER_PATH} from "@kf-web-library/utils/es/constants";
import {useScroll, useSize} from "ahooks";
import useEnhanceCssVars from "@/layouts/useEnhanceCssVars";
import useBreakpoint from "antd/es/grid/hooks/useBreakpoint";
import {MenuOutlined} from "@ant-design/icons";
import querystring from "query-string";
import {clearAuthInfo} from "@/utils/auth";
import {correspVal} from "@/utils/biz";

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  clearAuthInfo();
};

export default function Layout() {
  const {initialState, setInitialState} = useModel('@@initialState');
  const currentUserInfo = initialState?.currentUserInfo;
  const location = useLocation();

  const siteInfoReq = useRequest(() => API.queryFrontSiteAbout());
  const siteInfo = siteInfoReq?.data;

  const {locale} = useIntl();

  const navigate = useNavigate();
  // 获取当前路由
  const routes = useSelectedRoutes();
  const lastRoute = routes.at(-1)?.route as ISelectedRoute & { title?: string };

  const scroll = useScroll(document);
  const bodySize = useSize(document.querySelector('body'));
  const contentWidth = bodySize ? (bodySize.width > 1440 ? 1440 : bodySize.width) - 24 : 1440;
  const screens = useBreakpoint();
  const isMobile = !(screens.lg || screens.xxl || screens.xl);
  // 菜单选中样式
  const navActive = useCallback((props: {
    isActive: boolean;
  }) => {
    return props.isActive ? 'active' : undefined;
  }, []);

  const enhanceCssVars = useEnhanceCssVars();

  const [LayoutBgClassName, setLayoutBgClassName] = useState<LayoutBgClassName | undefined>(undefined);

  /**
   * 认证成功后的重定向地址
   */
  const authedRedirect = useMemo(() => {
    const search = new URLSearchParams(location.search);
    const redirect = search.get("redirect");
    const isIgnorePathname = [LOGIN_PATH, REGISTER_PATH, "/forgot", "/"].includes(location.pathname);
    console.log("isIgnorePathname", isIgnorePathname, location.pathname)
    return redirect ?? (isIgnorePathname ? undefined : window.location.href);
  }, [location.pathname]);


  const logout = useCallback(() => {
    setInitialState((s) => ({
      ...s,
      currentUserInfo: undefined,
      currentAuthInfo: undefined,
      frontMenus: undefined
    }));
    loginOut();
    if (location.pathname.startsWith("/mine")) {
      window.location.assign(`/`);
    } else {
      window.location.reload();
    }
    return;
  }, [location]);

  const isZhCN = locale === "zh-CN";
  const primaryQrCode = siteInfo?.qrCode?.find(q => !!q.primary)
  const qrCode = siteInfo?.qrCode || [];

  const navbar = (
    <ul className="hxiw-page-navbar">
      <li><NavLink to={"/"} end={true} className={navActive}><FormattedMessage id="menu.home"/></NavLink></li>
      <li><NavLink to={"/journal"} className={navActive}><FormattedMessage id="menu.journal"/></NavLink></li>
      <li><NavLink to={"/mall"} className={navActive}><FormattedMessage id="menu.mall"/></NavLink></li>
      <li><NavLink to={"/about"} className={navActive}><FormattedMessage id="menu.about"/></NavLink></li>
      {
        qrCode.length > 0 && (
          <li>
            <Popover
              placement="bottom"
              trigger="click"
              title={null}
              content={(
                <div className={"hx-mobile-qrcode-wrapper"}>
                  {
                    qrCode.filter(q => !!q.url).map((q, qindex) => {
                      return (
                        <div key={qindex}>
                          <QRCode size={100}
                                  color={"#000"}
                                  bgColor={"#FFF"}
                                  bordered={false}
                                  iconSize={25}
                                  icon="/qrcode_icon.png"
                                  value={q.url}/>
                          {correspVal(isZhCN, q.nameCn, q.nameEn)}
                        </div>
                      )
                    })
                  }
                </div>
              )}
            >
              <a className={"view-site-qrcode-btn"}><FormattedMessage id="menu.mobile"/></a>
            </Popover>
          </li>
        )
      }

      {
        (isMobile && !currentUserInfo) && (
          <>
            <li className={"navbar-divider"}></li>
            <li>
              <Link
                to={{
                  pathname: LOGIN_PATH,
                  search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
                }}
                className={"aside-btn"}
              >
                <FormattedMessage id="text.login"/>
              </Link>
            </li>
            <li>
              <Link
                to={{
                  pathname: REGISTER_PATH,
                  search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
                }}
                className={"aside-btn"}
              >
                <FormattedMessage id="text.register"/>
              </Link>
            </li>
          </>
        )
      }
    </ul>
  )


  return (
    <HxConfigContext.Provider value={{
      LayoutBgClassName: LayoutBgClassName,
      setLayoutBgClassName: setLayoutBgClassName,
      siteInfo,
      currentUserInfo,
      logout,
      authedRedirect,
      isZhCN,
      locale,
    }}>
      <ProConfigProvider>
        <Helmet>
          <title>{lastRoute?.title}</title>
        </Helmet>
        <div className={classNames("hxiw-page-layout", LayoutBgClassName)} style={{...enhanceCssVars}}>
          <header className={classNames("hxiw-page-header", {"hxiw-page-header-scroll": scroll && scroll.top > 10})}>
            <div className={"hxiw-page-header-content"}>
              <section className={"hxiw-page-header-content-left"}>
                <Link to={"/"} className={"hxiw-page-logo"}>
                  <img src={logo} alt={"logo"}/>
                </Link>
              </section>
              <section className={"hxiw-page-header-content-right"}>
                {!isMobile ? navbar : (
                  <Popover
                    placement="bottom"
                    trigger="click"
                    title={null}
                    content={navbar}
                    classNames={{
                      root: "hxiw-page-mobile-navbar-wrapper"
                    }}
                  >
                    <Button type="link" className={"hxiw-page-navbar-mobile-btn"}>
                      <MenuOutlined/>
                    </Button>
                  </Popover>
                )}
                <HeaderUserContainer/>
              </section>
            </div>
          </header>
          <main className={"hxiw-page-content-wrapper"}>
            <div className={"hxiw-page-content"} style={{
              width: contentWidth,
            }}>
              <Outlet/>
            </div>
          </main>
          <footer className={"hxiw-page-footer"}>
            <div className={"hxiw-page-footer-content"}>
              <div className={"hxiw-page-miscellaneous"}>
                <section className={"hxiw-page-miscellaneous-left"}>
                  <Link to={"/"} className={"hxiw-page-logo"}>
                    <img src={logo} alt={"logo"}/>
                  </Link>
                </section>
                <section className={"hxiw-page-miscellaneous-center"}>
                  <div className={"hxiw-page-contact-info"}>
                    <div><span><HxIcon type="hxicon-youbian"/><FormattedMessage
                      id="about.postal"/>:</span>{correspVal(isZhCN, siteInfo?.postCode.textCn, siteInfo?.postCode.textEn)}</div>
                    <div><span><HxIcon type="hxicon-youxiang"/><FormattedMessage
                      id="about.email"/>:</span>{correspVal(isZhCN, siteInfo?.email.textCn, siteInfo?.email.textEn)}</div>
                    <div><span><HxIcon type="hxicon-dizhi"/><FormattedMessage
                      id="about.address"/>:</span>{correspVal(isZhCN, siteInfo?.address.textCn, siteInfo?.address.textEn)}</div>
                  </div>
                  <div className={"hxiw-page-legal-info"}>
                    <Link to={"/about"}><FormattedMessage id="menu.about"/></Link>
                    <Link to={`/privacy-policy`}><FormattedMessage id="about.privacy"/></Link>
                    <Link to={`/legal-agreement`}><FormattedMessage id="about.legal"/></Link>
                    {/* <a><FormattedMessage id="about.site-map"/></a>*/}
                  </div>
                </section>
                {
                  primaryQrCode?.url && (
                    <section className={"hxiw-page-miscellaneous-right"}>
                      <QRCode size={100}
                              color={"#000"}
                              bgColor={"#FFF"}
                              bordered={true}
                              iconSize={25}
                              icon="/qrcode_icon.png"
                              value={primaryQrCode.url}/>
                    </section>
                  )
                }

              </div>
              <FriendLinksContainer/>
              <div className={"hxiw-page-website-record-info"}>
                <Space direction={isMobile ? "vertical" : "horizontal"}>
                  {
                    siteInfo?.siteNumber?.map((t, index) => {
                      if (!!t.url) {
                        return (
                          <a href={t.url} target={"_blank"}>
                            {correspVal(isZhCN, t.nameCn, t.nameEn)}
                          </a>
                        )
                      }
                      return <span>{correspVal(isZhCN, t?.nameCn, t?.nameEn)}</span>

                    })
                  }
                  {
                    siteInfo?.siteCopyright && (
                      <span>©{dayjs().year()} {correspVal(isZhCN, siteInfo?.siteCopyright?.textCn, siteInfo?.siteCopyright?.textEn)} <FormattedMessage
                        id="about.copyright"/></span>
                    )
                  }
                </Space>

              </div>
            </div>
          </footer>
        </div>
      </ProConfigProvider>
    </HxConfigContext.Provider>

  );
}
